import { HttpException, HttpStatus, Injectable, UseGuards } from '@nestjs/common';
import { UpdateStatisticDto } from './dto/update-statistic.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Statistics } from '@libs/db/models/statistics.model';
import { formatDate } from 'utils';
import { AttemptCustomer } from '@libs/db/models/attempt.model';
const path = require('path');
const Searcher = require('libs/xdb/index.js');
const dbPath = path.join(__dirname, '../libs/xdb/ip2region.xdb');

@Injectable()
export class StatisticsService {

  constructor(@InjectModel('Statistics') private readonly statisticsModel: Model<Statistics>, @InjectModel('AttemptCustomer') private readonly customerModel: Model<AttemptCustomer>) { }

  // 插入数据
  async create(ip: string) {
    try {
      console.log(ip,'统计数据IP');
      
      const searcher = Searcher.newWithFileOnly(dbPath)
      const data = await searcher.search(ip);
      let date = new Date();
      const playload = {
        ip,
        region: data.region,
        hours: date.getHours(),
        day: date.getDate(),
        month: date.getMonth() + 1,
        year: date.getFullYear()
      }
      const doc = await this.statisticsModel.create(playload)
      await doc.save()
      return '200';
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 根据时间查询列表数据，按照日为单位
  async queryDayData(body) {
    let data = {
      rows: [],
      total: 0
    }
    const todayStart = formatDate(new Date());
    const startTime = body.startTime ? new Date(body.startTime) : new Date(todayStart)
    const endTime = body.endTime ? new Date(body.endTime) : new Date()
    const count = await this.statisticsModel.find({ createdAt: { $gte: startTime, $lte: endTime }, region: { $regex: body.region } }).count()
    const rows = await this.statisticsModel.find({ createdAt: { $gte: startTime, $lte: endTime }, region: { $regex: body.region } }).skip((body.pageNum - 1) * body.pageSize).limit(body.pageSize).sort({createdAt:-1})
    data.rows = rows
    data.total = count
    return data
  }

  /**
   * @breif: 获取今日24时统计数据(数据图表),筛选大于传入的时间
   * @param {*} type : 1 按年份 2 按月份 3 按日期
   * @param {*} date : yyyy-MM-dd
   * @return {*}
   */
  async getReviewStatistic(type, date) {
    try {
      let groupby, hoursMap = [], endLen, endDay;
      let dateLoc = new Date(date)
      if (type === 1) {
        groupby = '$month';
        endLen = 12
        endDay = new Date(dateLoc.getTime() + 365 * 24 * 60 * 60 * 1000);
      } else if (type === 2) {
        groupby = '$day'
        endLen = new Date(dateLoc.getFullYear(), dateLoc.getMonth() + 1, 0).getDate(); // 传递过来月份的天数总数量，如果没传，则默认当月;
        endDay = new Date(dateLoc.getFullYear(), dateLoc.getMonth() + 1, 0)
      } else {
        groupby = '$hours'
        endLen = 24
        endDay = new Date(dateLoc.getTime() + 24 * 60 * 60 * 1000)
      }
      const res = await this.statisticsModel.aggregate([
        {
          $match: {
            $and: [
              { createdAt: { $gte: dateLoc, $lte: endDay } }
            ]
          }
        },
        {
          $group: {
            _id: groupby,
            count: { $sum: 1 }
          }
        }
      ])
      for (let i = 1; i <= endLen; i++) {
        let idx = res.findIndex(item => item._id == i);
        if (idx === -1) {
          hoursMap.push({ _id: i + '', count: 0 })
        } else {
          hoursMap.push(res[idx])
        }
      }
      return hoursMap
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  /**
   * @breif: 获取本月列表数据数据(可分页查询,没用了)
   * @return {*}
   */
  async getMonthData(body) {
    try {
      let data = {
        rows: [],
        total: 0
      }
      const todayStart = formatDate(new Date());
      const startTime = body.startTime ? new Date(body.startTime) : new Date(todayStart)
      const endTime = body.endTime ? new Date(body.endTime) : new Date()
      const count = await this.statisticsModel.find({ createdAt: { $gte: startTime, $lte: endTime }, region: { $regex: body.region } }).count()
      const rows = await this.statisticsModel.find({ createdAt: { $gte: startTime, $lte: endTime }, region: { $regex: body.region } }).skip((body.pageNum - 1) * body.pageSize).limit(body.pageSize)
      data.rows = rows
      data.total = count
      return data
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }


  /**
   * @breif: 获取月统计数据（图表）
   * @return {*}
   */
  async getAwsStatistic(type,date) {
    try {
      let groupby, hoursMap = [], endLen, endDay;
      let dateLoc = new Date(date)
      if (type === 1) {
        groupby = '$month';
        endLen = 12
        endDay = new Date(dateLoc.getTime() + 365 * 24 * 60 * 60 * 1000);
      } else if (type === 2) {
        groupby = '$day'
        endLen = new Date(dateLoc.getFullYear(), dateLoc.getMonth() + 1, 0).getDate(); // 传递过来月份的天数总数量，如果没传，则默认当月;
        endDay = new Date(dateLoc.getFullYear(), dateLoc.getMonth() + 1, 0)
      } else {
        groupby = '$hours'
        endLen = 24
        endDay = new Date(dateLoc.getTime() + 24 * 60 * 60 * 1000)
      }
      const res = await this.customerModel.aggregate([
        {
          $match: {
            $and: [
              { createdAt: { $gte: dateLoc, $lte: endDay } }
            ]
          }
        },
        {
          $group: {
            _id: groupby,
            count: { $sum: 1 }
          }
        }
      ])
      for (let i = 1; i <= endLen; i++) {
        let idx = res.findIndex(item => item._id == i);
        if (idx === -1) {
          hoursMap.push({ _id: i + '', count: 0 })
        } else {
          hoursMap.push(res[idx])
        }
      }
      return hoursMap
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} statistic`;
  }

  update(id: number, updateStatisticDto: UpdateStatisticDto) {
    return `This action updates a #${id} statistic`;
  }

  remove(id: number) {
    return `This action removes a #${id} statistic`;
  }
}
